package com.example.battle.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.battle.common.GlobalResult;
import com.example.battle.common.WechatUtil;
import com.example.battle.entity.sys.Account;
import com.example.battle.entity.sys.Rank;
import com.example.battle.repository.AccountRepository;
import com.example.battle.repository.RankRepository;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Data
@Slf4j
@RestController
public class AccountController {
    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private RankRepository rankRepository;

    @RequestMapping("index")
    public Account index() {
        // accountRepository.findByAvatarUrl("https://wx.qlogo.cn/mmopen/vi_32/lh7eyJbvkL4E2re9ictRw4nrTX91wvPofJ89ibyCRDGpKhTYcvibMvpJMX3eIz9Q18ibkXc5jgSm1R8rjalvKbPDzQ/132");
        return null;
    }

    @RequestMapping("/websocket/friendBattle")
    public void friendMatch(@RequestParam(value = "avatarUrl") String avatarUrl){

    }

    @RequestMapping("getRank")
    public List getRank(){
        List<Rank> list = rankRepository.findAll();
        Collections.sort(list,new Comparator<Rank>(){
            // 排行榜排序
            @Override public int compare(Rank o1,Rank o2){
                return Integer.parseInt(o2.getScore()) - Integer.parseInt(o1.getScore());
            }
        });
        return list;
    }

    @RequestMapping("setScore")
    public void setScore(@RequestParam(value = "avatarUrl") String avatarUrl,
                         @RequestParam(value = "score") String score,
                         @RequestParam(value = "nickName") String nickName){
        Rank ranks = rankRepository.findByavatarUrl(avatarUrl);
        if(ranks == null){
            Rank rank = new Rank();
            rank.setScore(score);
            rank.setAvatarUrl(avatarUrl);
            rank.setNickName(nickName);
            rankRepository.save(rank);
        }else{
            if(Integer.parseInt(score) > Integer.parseInt(ranks.getScore())){
                ranks.setScore(score);
                rankRepository.save(ranks);
            }
        }
    }

    @PostMapping("wx/login")
    @ResponseBody
    public GlobalResult user_login(@RequestParam(value = "code", required = false) String code,
                                   @RequestParam(value = "rawData", required = false) String rawData,
                                   @RequestParam(value = "signature", required = false) String signature,
                                   @RequestParam(value = "encrypteData", required = false) String encrypteData,
                                   @RequestParam(value = "iv", required = false) String iv) {
        // 用户非敏感信息：rawData
        // 签名：signature
        JSONObject rawDataJson = JSON.parseObject(rawData);
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");

        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        if (!signature.equals(signature2)) {
            return GlobalResult.build(500, "签名校验失败", null);
        }
        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
        Account account = this.accountRepository.findByopenId(openid);
        // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
        String skey = UUID.randomUUID().toString();
        if (account == null) {
            // 用户信息入库
            String nickName = rawDataJson.getString("nickName");
            String avatarUrl = rawDataJson.getString("avatarUrl");
            String gender = rawDataJson.getString("gender");
            String city = rawDataJson.getString("city");
            String country = rawDataJson.getString("country");
            String province = rawDataJson.getString("province");

            account = new Account();
            account.setOpenId(openid);
            account.setSkey(skey);
            account.setCreateTime(new Date());
            account.setLastVisitTime(new Date());
            account.setSessionKey(sessionKey);
            account.setCity(city);
            account.setProvince(province);
            account.setCountry(country);
            account.setAvatarUrl(avatarUrl);
            account.setGender(Integer.parseInt(gender));
            account.setNickName(nickName);

            this.accountRepository.save(account);
        } else {
            String avatarUrl = rawDataJson.getString("avatarUrl");
            account.setAvatarUrl(avatarUrl);
            // 已存在，更新用户登录时间
            account.setLastVisitTime(new Date());
            // 重新设置会话skey
            account.setSkey(skey);
            this.accountRepository.save(account);
        }
        //encrypteData比rowData多了appid和openid
        JSONObject userInfo = WechatUtil.getUserInfo(encrypteData, sessionKey, iv);
        //6. 把新的skey返回给小程序
        GlobalResult result = GlobalResult.build(200, null, skey);
        return result;
    }
}
